package org.dczl.system.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.dczl.common.core.utils.MapstructUtils;
import org.dczl.common.core.utils.StringUtils;
import org.dczl.common.mybatis.core.page.TableDataInfo;
import org.dczl.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.dczl.common.redis.utils.RedisUtils;
import org.dczl.system.domain.DpProject;
import org.dczl.system.domain.vo.DpProjectVo;
import org.dczl.system.domain.vo.DpRatioVo;
import org.dczl.system.domain.vo.DpWeatherVo;
import org.dczl.system.mapper.DpProjectMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.dczl.system.domain.bo.DpLabBo;
import org.dczl.system.domain.vo.DpLabVo;
import org.dczl.system.domain.DpLab;
import org.dczl.system.mapper.DpLabMapper;
import org.dczl.system.service.IDpLabService;

import java.time.Duration;
import java.util.*;

/**
 * 实验室Service业务层处理
 *
 * @author jia
 * @date 2025-04-16
 */
@RequiredArgsConstructor
@Service
@Slf4j
public class DpLabServiceImpl implements IDpLabService {

    private final DpLabMapper baseMapper;

    private final DpProjectMapper projectMapper;

    @Value("${cityCode}")
    private String cityCode;

    @Override
    public DpLabVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }


    @Override
    public TableDataInfo<DpLabVo> queryPageList(DpLabBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<DpLab> lqw = buildQueryWrapper(bo);
        Page<DpLabVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }


    @Override
    public List<DpLabVo> queryList(DpLabBo bo) {
        LambdaQueryWrapper<DpLab> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    @Override
    public List<DpLabVo> daPing() {
        List<DpLabVo> list = baseMapper.queryList();
        for (DpLabVo dpLabVo : list) {
            DpProjectVo project = projectMapper.selectVoOne(Wrappers.lambdaQuery(DpProject.class)
                    .eq(DpProject::getLabId, dpLabVo.getId())
                    .ge(DpProject::getStartTime, DateUtil.today())
                    .orderByAsc(DpProject::getStartTime)
                    .last("limit 1"));
            if (Objects.isNull(project)) {
                project = projectMapper.selectVoOne(Wrappers.lambdaQuery(DpProject.class)
                        .eq(DpProject::getLabId, dpLabVo.getId())
                        .orderByDesc(DpProject::getStartTime)
                        .last("limit 1"));
            }
            dpLabVo.setProject(project);
        }
        return list;
    }

    @Override
    public List<DpRatioVo> ratio() {
        List<DpRatioVo> list = new ArrayList<>();
        List<DpLabVo> labVos = baseMapper.selectVoList();
        Long count = projectMapper.getCount(Wrappers.query(DpProject.class).eq("del_flag", 0));
        for (DpLabVo dpLabVo : labVos) {
            DpRatioVo dpRatioVo = new DpRatioVo();
            dpRatioVo.setName(dpLabVo.getName());
            Long now = projectMapper.getCount(Wrappers.query(DpProject.class).eq("del_flag", 0).eq("lab_id", dpLabVo.getId()));
            dpRatioVo.setNum(NumberUtil.round(NumberUtil.mul(NumberUtil.div(now, count), 100), 0));
            list.add(dpRatioVo);
        }
        return list;
    }

    @Override
    public List<DpLabVo> list() {
        List<DpLabVo> list = baseMapper.queryList();
        for (DpLabVo dpLabVo : list) {
            dpLabVo.setProjects(projectMapper.selectVoList(Wrappers.lambdaQuery(DpProject.class)
                    .eq(DpProject::getLabId, dpLabVo.getId())
                    .orderByDesc(DpProject::getStartTime)));
        }
        return list;
    }

    @Override
    public DpWeatherVo weather() {
        String rediskey = "weather";
        if (RedisUtils.hasKey(rediskey)) {
            return RedisUtils.getCacheObject(rediskey);
        }
        String url = "http://t.weather.itboy.net/api/weather/city/" + cityCode;
        String result = HttpUtil.get(url);
        log.info("天气信息：{}", result);
        JSONObject data = JSONUtil.parseObj(result).getJSONObject("data");
        DpWeatherVo dpWeatherVo = new DpWeatherVo();
        JSONArray forecast = data.getJSONArray("forecast");
        dpWeatherVo.setWendu(data.getStr("wendu"));
        dpWeatherVo.setType(forecast.getJSONObject(0).getStr("type"));
        dpWeatherVo.setLow(forecast.getJSONObject(0).getStr("low"));
        dpWeatherVo.setHigh(forecast.getJSONObject(0).getStr("high"));
        RedisUtils.setCacheObject(rediskey, dpWeatherVo, Duration.ofHours(2));
        return dpWeatherVo;
    }

    private LambdaQueryWrapper<DpLab> buildQueryWrapper(DpLabBo bo) {
        LambdaQueryWrapper<DpLab> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(bo.getName()), DpLab::getName, bo.getName());
        lqw.eq(StringUtils.isNotBlank(bo.getType()), DpLab::getType, bo.getType());
        lqw.eq(StringUtils.isNotBlank(bo.getLinkUrl()), DpLab::getLinkUrl, bo.getLinkUrl());
        lqw.eq(StringUtils.isNotBlank(bo.getLocation()), DpLab::getLocation, bo.getLocation());
        return lqw;
    }

    /**
     * 新增实验室
     */
    @Override
    @Transactional
    public Boolean insertByBo(DpLabBo bo) {
        DpLab add = MapstructUtils.convert(bo, DpLab.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改实验室
     */
    @Override
    @Transactional
    public Boolean updateByBo(DpLabBo bo) {
        DpLab update = MapstructUtils.convert(bo, DpLab.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(DpLab entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除实验室
     */
    @Override
    @Transactional
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }
}
